import app from '../app.js';
import config from '../config.js';
import Base_tools_class from '../core/base-tools.js';
import Tesseract from 'tesseract.js';
import { message, Modal } from 'antd';

class Denoise_class extends Base_tools_class {
  constructor(ctx) {
    super();
    this.ctx = ctx;
    this.name = 'text_deepen';
  }

  load() {
    document.addEventListener(
      'keydown',
      (e) => {
        if (config.TOOL.name !== this.name) return;
        if (e.keyCode === 13) {
          this.applyDenoise();
        }
      },
      false
    );
  }

  /**
   * 启动文字加深功能
   */
  applyDenoise() {
    if (!config.layer || !config.layer.link) {
      message.warning('当前没有选中的图层');
      return;
    }

    const params = this.getParams();
    const canvas = this.Base_layers.convert_layer_to_canvas(config.layer.id);
    const ctx = canvas.getContext('2d');
    const closeLoading = message.loading('文字识别中，请稍候..', 0);

    const prefix =
      process.env.NODE_ENV === 'production'
        ? '/prs/static/js/pages/tesseract'
        : '../../../src/js/tesseract';

    Tesseract.recognize(canvas, 'chi_sim', {
      langPath: prefix + '/chi_sim',
      workerPath: prefix + '/worker.min.js',
      corePath: prefix + '/tesseract-core-simd-lstm.wasm.js',
    })
    .then(({ data }) => {
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const { lines } = data;

      // 创建一个与 canvas 大小相同的掩码，用于标记需要加深的像素
      const mask = new Array(canvas.height).fill().map(() => new Array(canvas.width).fill(false));

      lines.forEach((line) => {
        line.words.forEach((word) => {
          const { x0, y0, x1, y1 } = word.bbox;

          // 遍历每个字符的像素，标记需要加深的区域
          for (let y = Math.max(0, y0); y < Math.min(canvas.height, y1); y++) {
            for (let x = Math.max(0, x0); x < Math.min(canvas.width, x1); x++) {
              const index = (y * canvas.width + x) * 4;
              const r = imageData.data[index];
              const g = imageData.data[index + 1];
              const b = imageData.data[index + 2];

              // 如果像素不是白色（亮度低于阈值），则标记为需要加深
              const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
              if (luminance < 240) {
                mask[y][x] = true;
              }
            }
          }
        });
      });

      // 根据掩码加深像素
      for (let y = 0; y < canvas.height; y++) {
        for (let x = 0; x < canvas.width; x++) {
          if (mask[y][x]) {
            const index = (y * canvas.width + x) * 4;
            const power = params.power;

            imageData.data[index] = Math.max(0, imageData.data[index] - power); // Red
            imageData.data[index + 1] = Math.max(0, imageData.data[index + 1] - power); // Green
            imageData.data[index + 2] = Math.max(0, imageData.data[index + 2] - power); // Blue
          }
        }
      }

      // 将修改后的图像数据更新回图层
      ctx.putImageData(imageData, 0, 0);
      this.Base_layers.update_layer_image(canvas, config.layer.id);
      closeLoading();
      message.success('文字加深完成！');
    })
    .catch((err) => {
      closeLoading();
      message.error('文字识别失败：');
      console.error(err);
    });
  }

  /**
   * 激活工具时触发
   */
  onClickFix() {
    this.applyDenoise();
  }
}

export default Denoise_class;